package top.dark.product.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import top.dark.common.utils.PageUtils;
import top.dark.common.utils.Query;

import top.dark.product.dao.BrandDao;
import top.dark.product.dao.CategoryBrandRelationDao;
import top.dark.product.entity.BrandEntity;
import top.dark.product.service.BrandService;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),wrapper
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void updateDetial(BrandEntity brand) {
        // 1、更新品牌数据
        this.updateById(brand);
        // 2、更新品牌关联分类表中的冗余数据，保证数据的一致性
        categoryBrandRelationDao.updateBrandName(brand.getBrandId(),brand.getName());

        // TODO 更新其余需要保证冗余数据一致性的表
    }

    @Override
    public List<BrandEntity> brandInfoByIds(List<Long> brandIds) {
        return baseMapper.selectList(new QueryWrapper<BrandEntity>().in("brand_id", brandIds));
    }

}